package com.j180.spring_jwt_demo.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final String KEY="$%#HDSDS434089DSM$#JBHGF@#!HJH76^$%$$#";

    private JWTUtil(){

    }
    /**
     * 获得jwt
     * @param map  有效负载的内容
     * @param expires 过期时间  以分钟为计算单位
     * @return  token
     */
    public static  String  getToken(Map<String,String> map, int expires){

        //创建一个有效期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,expires);
        Date time = calendar.getTime();
        JWTCreator.Builder builder = JWT.create();
        //进行有效负载的封装
        map.forEach((key,val)->{
            builder.withClaim(key,val);
        });
        //设置有效器
        builder.withExpiresAt(time);

        String token =builder.sign(Algorithm.HMAC256(KEY));
          return token;
    }

    /**
     * 验证token
     * @param token  token
     * @return  解码后的jwt
     */
    public static DecodedJWT verifyToken(String token){

        JWTVerifier build = JWT.require(Algorithm.HMAC256(KEY)).build();

        DecodedJWT decodedJWT = build.verify(token);

        return decodedJWT;
    }

}
